package com.bdqn.oa.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * Druide连接池工具
 */
public class DruidUtils {
    /**
     * 数据源
     */
    public static DataSource dataSource;
    /**
     * 本地线程 一个线程共享一个变量
     */
    public static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    static{
        try {
            // 加载属性集配置文件
            InputStream input = DruidUtils.class.getClassLoader().getResourceAsStream("database.properties");
            Properties properties = new Properties();
            properties.load(input);
            // 创建数据源工厂
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据源
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }
    /**
     * 获得连接
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        try{
            connection = threadLocal.get();
            if(connection == null){
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void close(){
        Connection connection = null;
        try{
            connection = threadLocal.get();
            if(connection != null){
                connection.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
